<script setup>
  /**
   * ImageUpload with upload logic to upload to a specific file store
   */

  import { computed, onMounted, ref } from 'vue'
  import ImageUpload from '@/components/forms/ImageUpload.vue'
  import { useConstStore } from '@/stores/const'
  import { inject } from 'vue';

  const props = defineProps({
    name: { type: String, required: true },
    label: { type: String, default: '' },
    downloadLabel: { type: String, default: 'Choisir un fichier' },
    editLabel: { type: String, default: 'Choisir un autre fichier' },
    deleteLabel: { type: String, default: 'Supprimer le fichier' },
    icon: { type: String, default: 'pen' },
    value: { type: Number || null, default: null },
    description: { type: String, default: '' },
    fileInfo: { type: Object || null, default: null },
    deletePermission: { type: Boolean || null, default: true },
    required: { type: Boolean || null, default: false },
    parentId: { type: Number, required: true },
  })


  const endiConfig = ref({})
  const constStore = useConstStore()
  const fileStore = inject(`fileStore-${props.name}`)

  const emits = defineEmits(['changeValue', 'blurValue'])


  // Used to change cache-busting key in image URL
  const lastUploadDate = ref(0)

  const onFileSelected = async (fileObject) => {
    const formData = new FormData()
    formData.append("upload", fileObject)
    formData.append("description", fileObject.name)

    console.log('onFileSelected', props, props.value)
    if (props.fileInfo && props.fileInfo.id) {
      const returned = await fileStore.updateFile(formData, props.fileInfo.id)
      lastUploadDate.value = new Date().getTime()
      emits("changeValue", returned)
    } else {
      if (props.parentId) {
        formData.append("parent_id", props.parentId)
      }
      const returned = await fileStore.addFile(formData)
      emits("changeValue", returned)
    }
  }

 const onDelete = async function(){
    await fileStore.deleteFile(props.fileInfo.id)
    emits("changeValue", null)
 }

 const previewUrl = computed(() => props.fileInfo ? `/files/${props.fileInfo.id}?action=download&_cache_bust=${lastUploadDate.value}` : null)

  onMounted(async () => {
    endiConfig.value = await constStore.loadConst('config')
  })
</script>

<template>

      <ImageUpload
        :name="'_' + props.name"
        :label="props.label"
        :downloadlabel='props.downloadLabel'
        :editlabel='props.editLabel'
        :deletelabel='props.deletelabel'
        :icon="props.icon"
        :description="props.description"
        :fileInfo='props.fileInfo'
        :max-size="endiConfig.max_allowed_file_size"
        @changeValue="onFileSelected"
        @unsetValue="onDelete"
        :file-url="previewUrl"
      />

</template>
